package org.jeecg.modules.purchase.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.jeecg.common.exception.ServiceException;
import org.jeecg.modules.purchase.entity.PurchaseStock;
import org.jeecg.modules.purchase.mapper.PurchaseStockMapper;
import org.jeecg.modules.purchase.service.IPurchaseStockService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * @Description: 库存
 * @Author: jeecg-boot
 * @Date:   2022-11-14
 * @Version: V1.0
 */
@Service
public class PurchaseStockServiceImpl extends ServiceImpl<PurchaseStockMapper, PurchaseStock> implements IPurchaseStockService {
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addStock(PurchaseStock purchaseStock) {
        // 判断库存是否已经存在并且价格相同的物品
        LambdaQueryWrapper<PurchaseStock> wrapper = creatWrapper(purchaseStock);
        PurchaseStock goodsStock = this.getOne(wrapper);
        if (ObjectUtil.isNotEmpty(goodsStock)){
            BigDecimal totalNumber = goodsStock.getTotalNumber();
            BigDecimal sum = totalNumber.add(purchaseStock.getTotalNumber());
            // 实际库存小于要出库的数量
            if (sum.compareTo(BigDecimal.ZERO) < 0){
                throw new ServiceException("实际库存小于出库数量");
            }
            goodsStock.setTotalNumber(sum);
            this.updateById(goodsStock);
        }
        else if (purchaseStock.getTotalNumber().compareTo(BigDecimal.ZERO) > 0){
            this.save(purchaseStock);
        }
        else if (purchaseStock.getTotalNumber().compareTo(BigDecimal.ZERO) < 0){
            // 需要减少库存数量，但没有对应库存
            throw new ServiceException("库存不存在");
        }
    }

    @Override
    public BigDecimal findTotalNumber(String repositoryCode, String goodsCode, BigDecimal goodsUnitPrice) {
        LambdaQueryWrapper<PurchaseStock> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PurchaseStock::getRepositoryCode,repositoryCode);
        wrapper.eq(PurchaseStock::getGoodsCode,goodsCode);
        wrapper.eq(PurchaseStock::getGoodsUnitPrice,goodsUnitPrice);
        PurchaseStock purchaseStock = this.getOne(wrapper);
        return purchaseStock.getTotalNumber();
    }


    private LambdaQueryWrapper<PurchaseStock> creatWrapper(PurchaseStock purchaseStock){
        LambdaQueryWrapper<PurchaseStock> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PurchaseStock::getGoodsCode,purchaseStock.getGoodsCode());
        wrapper.eq(PurchaseStock::getGoodsUnitPrice,purchaseStock.getGoodsUnitPrice());
        wrapper.eq(PurchaseStock::getRepositoryCode,purchaseStock.getRepositoryCode());
        return wrapper;
    }

}
